package com.erp.erp_ui.warehouse.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.enums.*;
import com.erp.erp_entitys.warehouse.entity.*;
import com.erp.erp_entitys.warehouse.req.*;
import com.erp.erp_entitys.warehouse.rsp.*;
import com.erp.erp_servers.warehouse.*;
import com.erp.erp_ui.warehouse.enums.DataIsValidEnum;
import com.erp.erp_ui.warehouse.enums.ResourceSamplesTypeEnum;
import com.erp.erp_ui.warehouse.req.*;
import com.erp.erp_ui.warehouse.vo.*;
import com.erp.utils.DateUtils;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.erp.utils.StringUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName : ResourceSamplesService
 * @Description : 资源样品业务逻辑层
 * @Author : lst
 * @Date: 2020-11-28 16:08
 */
@Service
public class ResourceSamplesService {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ResourceSamplesService.class);


    /**
     * 资源样品接口
     */
    private final IResourceSamplesService resourceSamplesService;


    /**
     * 资源样品明细接口
     */
    private final IResourceSamplesDetailService resourceSamplesDetailService;

    /**
     * 库存接口
     */
    private final IStockService stockService;


    @Autowired
    public ResourceSamplesService(IResourceSamplesService resourceSamplesService,
                                  IResourceSamplesDetailService resourceSamplesDetailService,
                                  IStockService stockService) {
        this.resourceSamplesService = resourceSamplesService;
        this.resourceSamplesDetailService = resourceSamplesDetailService;
        this.stockService = stockService;
    }

    /**
     * 仓库管理-资源样品-首页-分页查询
     * @param req 查询条件
     * @return 分页结果
     */
    public PageInfo<ResourceSamplesPageListVo> getResourceSamplesListByPage(ResourceSamplesPageListReq req){
        if (StringUtils.isEmpty(req.getOperationCode()) && StringUtils.isEmpty(req.getDeptOperationCode())) {
            return new PageInfo(new ArrayList());
        }
        //初始化查询条件
        ResourceSamplesListReq pageReq = new ResourceSamplesListReq();
        //赋值
        BeanUtils.copyProperties(req, pageReq);
        //调用接口获取查询结果
        List<ResourceSamplesEntity> resourceSamplesList = resourceSamplesService.getResourceSamplesList(pageReq);
        //获取分页信息
        PageInfo pageInfo = new PageInfo(resourceSamplesList);
        //初始化回参集合
        List<ResourceSamplesPageListVo> pageVos = new ArrayList<>();
        if(CollectionUtils.isEmpty(resourceSamplesList)){
            pageInfo.setList(pageVos);
            return pageInfo;
        }
        for(ResourceSamplesEntity other : resourceSamplesList){
            ResourceSamplesPageListVo pageVo = new ResourceSamplesPageListVo();
            BeanUtils.copyProperties(other, pageVo);
            //日期转换
            pageVo.setCreateDate(DateUtils.format(other.getCreateDate(), DateUtils.DATE_PATTERN));
            //状态转换
            pageVo.setStatusStr(OperationStatusEnum.getDescById(other.getStatus()));
            //业务类型转换
            pageVo.setTypeStr(ResourceSamplesTypeEnum.getDescById(other.getType()));

            pageVos.add(pageVo);
        }
        pageInfo.setList(pageVos);
        return pageInfo;
    }

    /**
     * 首页-获取资源样品库存分页信息
     * @param req 查询条件
     * @return 分页结果
     */
    public PageInfo<ResourceSamplesStockPageListVo> getResourceSamplesStockListByPage(ResourceSamplesStockPageListReq req){
        //初始化查询条件
        ResourceSamplesStockListReq pageReq = new ResourceSamplesStockListReq();
        //赋值
        BeanUtils.copyProperties(req, pageReq);
        //调用接口获取查询结果
        List<ResourceSamplesStockListRsp> resourceSamplesList = resourceSamplesDetailService.getResourceSamplesStockList(pageReq);
        //获取分页信息
        PageInfo pageInfo = new PageInfo(resourceSamplesList);
        //初始化回参集合
        List<ResourceSamplesStockPageListVo> pageVos = new ArrayList<>();
        if(CollectionUtils.isEmpty(resourceSamplesList)){
            pageInfo.setList(pageVos);
            return pageInfo;
        }
        for(ResourceSamplesStockListRsp other : resourceSamplesList){
            ResourceSamplesStockPageListVo pageVo = new ResourceSamplesStockPageListVo();
            BeanUtils.copyProperties(other, pageVo);

            pageVos.add(pageVo);
        }
        pageInfo.setList(pageVos);
        return pageInfo;
    }


    /**
     * 获取String类型不为空数据
     *
     * @param value 目标数据
     * @return 不为空数据
     */
    private String getNotNullOfStringInfo(String value) {
        if (StringUtils.isEmpty(value)) {
            return "";
        } else {
            return value;
        }
    }

    /**
     * 获取BigDecimal类型不为空的数据
     *
     * @param value 目标数据
     * @return 不为空数据
     */
    private BigDecimal getNotNullOfBigDecimalInfo(BigDecimal value) {
        if (StringUtil.isNotEmpty(value)) {
            return value;
        } else {
            return new BigDecimal("0");
        }
    }
    /**
     * 首页-获取库存明细统计分页信息
     * @param req 查询条件
     * @return 分页结果
     */
    public PageInfo<InventoryDetailStatisticsPageVo> getInventoryDetailStatisticsReqListByPage(InventoryDetailStatisticsPageReq req){
        if (StringUtils.isEmpty(req.getOperationCode()) && StringUtils.isEmpty(req.getDeptOperationCode())) {
            return new PageInfo(new ArrayList<>());
        }
        //初始化查询条件
        InventoryDetailStatisticsReq pageReq = new InventoryDetailStatisticsReq();
        //赋值
        BeanUtils.copyProperties(req, pageReq);
        //调用接口获取查询结果
        List<InventoryDetailStatisticsRsp> inventoryDetailList = resourceSamplesDetailService.getInventoryDetailStatisticsReqList(pageReq);

        //获取分页信息
        PageInfo pageInfo = new PageInfo(inventoryDetailList);
        //初始化回参集合
        List<InventoryDetailStatisticsPageVo> pageVos = new ArrayList<>();
        if(CollectionUtils.isEmpty(inventoryDetailList)){
            pageInfo.setList(pageVos);
            return pageInfo;
        }
        for(InventoryDetailStatisticsRsp other : inventoryDetailList){
            InventoryDetailStatisticsPageVo pageVo = new InventoryDetailStatisticsPageVo();

            BeanUtils.copyProperties(other, pageVo);

            if (other.getType()==1){
                pageVo.setTypeStr("登记");
            }else if (other.getType()==2){
                pageVo.setTypeStr("领出");
            }else {
                pageVo.setTypeStr("");
            }

            switch (other.getStatus()){
                case 1:
                    pageVo.setStatusStr("草稿箱");
                    break;
                case 2:
                    pageVo.setStatusStr("待批箱");
                    break;
                case 3:
                    pageVo.setStatusStr("已批箱");
                    break;
                case 4:
                    pageVo.setStatusStr("完成箱");
                    break;
                case 5:
                    pageVo.setStatusStr("垃圾箱");
                    break;
            }
            pageVo.setCreateDateStr(DateUtils.format(other.getCreateDate(), DateUtils.DATE_PATTERN));

            pageVos.add(pageVo);
        }
        pageInfo.setList(pageVos);
        return pageInfo;
    }
    /**
     * 获取库存明细统计信息--导出
     * @param req
     * @return
     */
    public JSONObject getInventoryDetailStatisticsReqListExport(InventoryDetailStatisticsPageReq req){
        //初始化查询条件
        InventoryDetailStatisticsReq pageReq = new InventoryDetailStatisticsReq();
        //赋值
        BeanUtils.copyProperties(req, pageReq);
        //调用接口获取查询结果
        List<InventoryDetailStatisticsRsp> inventoryDetailList = resourceSamplesDetailService.getInventoryDetailStatisticsReqList(pageReq);
        //初始化回参集合
        List<InventoryDetailStatisticsPageVo> listVo = new ArrayList<>();
        for(InventoryDetailStatisticsRsp other : inventoryDetailList){
            InventoryDetailStatisticsPageVo pageVo = new InventoryDetailStatisticsPageVo();

            BeanUtils.copyProperties(other, pageVo);

            if (other.getType()==1){
                pageVo.setTypeStr("登记");
            }else if (other.getType()==2){
                pageVo.setTypeStr("领出");
            }else {
                pageVo.setTypeStr("");
            }
            switch (other.getStatus()){
                case 1:
                    pageVo.setStatusStr("草稿箱");
                    break;
                case 2:
                    pageVo.setStatusStr("待批箱");
                    break;
                case 3:
                    pageVo.setStatusStr("已批箱");
                    break;
                case 4:
                    pageVo.setStatusStr("完成箱");
                    break;
                case 5:
                    pageVo.setStatusStr("垃圾箱");
                    break;
            }
            pageVo.setCreateDateStr(DateUtils.format(other.getCreateDate(), DateUtils.DATE_PATTERN));
            listVo.add(pageVo);
        }

        JSONObject obj = new JSONObject();
        //获取excel的title信息
        JSONArray titleList = getTitleInventoryDetailStatistics();
        JSONArray data = new JSONArray();
        data.add(titleList);
        if(CollectionUtils.isEmpty(listVo)){
            obj.put("data", data);
            return obj;
        }
        //封装数据
        getInventoryDetailStatisticsInfo(data, listVo);

        obj.put("data", data);
        return obj;
    }
    private JSONArray getTitleInventoryDetailStatistics() {
        JSONArray obj = new JSONArray();
        obj.add("序号");
        obj.add("单据类型");
        obj.add("单据编号");
        obj.add("业务类型");
        obj.add("创建日期");
        obj.add("操作员");
        obj.add("产品仓库");
        obj.add("产品编码");
        obj.add("规格编码");
        obj.add("规格说明");
        obj.add("中文名称");
        obj.add("英文名称");
        obj.add("中文描述");
        obj.add("英文描述");
        obj.add("单价");
        obj.add("数量");
        obj.add("单位");
        obj.add("货位");
        obj.add("批次");
        obj.add("供应商名称");
        return obj;
    }
    private void getInventoryDetailStatisticsInfo(JSONArray data,List<InventoryDetailStatisticsPageVo> listVo){
        //数量
        BigDecimal productNum = new BigDecimal("0");
        Integer i=0;
        for (InventoryDetailStatisticsPageVo vo: listVo) {
            JSONArray infoList = new JSONArray();
            infoList.add(++i);
            infoList.add(getNotNullOfStringInfo(vo.getStatusStr()));
            infoList.add(getNotNullOfStringInfo(vo.getBillNo()));
            infoList.add(getNotNullOfStringInfo(vo.getTypeStr()));
            infoList.add(getNotNullOfStringInfo(vo.getCreateDateStr()));
            infoList.add(getNotNullOfStringInfo(vo.getOperationName()));
            infoList.add(getNotNullOfStringInfo(vo.getDetailWarehouseName()));
            infoList.add(getNotNullOfStringInfo(vo.getProductCode()));
            infoList.add(getNotNullOfStringInfo(vo.getSpecificationCode()));
            infoList.add(getNotNullOfStringInfo(vo.getSpecificationExplanation()));
            infoList.add(getNotNullOfStringInfo(vo.getProductCname()));
            infoList.add(getNotNullOfStringInfo(vo.getProductEname()));
            infoList.add(getNotNullOfStringInfo(vo.getProductCdesc()));
            infoList.add(getNotNullOfStringInfo(vo.getProductEdesc()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getUnitPrice()));
            infoList.add(getNotNullOfBigDecimalInfo(vo.getProductNum()));
            infoList.add(getNotNullOfStringInfo(vo.getProductUnit()));
            infoList.add(getNotNullOfStringInfo(vo.getArticleNo()));
            infoList.add(getNotNullOfStringInfo(vo.getLotNo()));
            infoList.add(getNotNullOfStringInfo(vo.getSupplierName()));

            if(StringUtil.isNotEmpty(vo.getProductNum())){
                productNum = productNum.add(vo.getProductNum());
            }

            data.add(infoList);
        }
        //合计
        JSONArray infoList = new JSONArray();
        infoList.add("合计");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add(productNum);
        infoList.add("");
        infoList.add("");
        infoList.add("");
        infoList.add("");
        data.add(infoList);
    }
    /**
     * 仓库管理-资源样品-登记新增、修改
     * @param req 新增、修改参数实体
     * @param creator 创建人
     * @param createNo 创建人编码
     * @return 新增、修改结果
     */
    @Transactional(rollbackFor = Exception.class)
    public R add(AddResourceSamplesReq req, String creator, String createNo){
        boolean billNoCheckFlag = (null != req.getId() && req.getBillNo().equals(req.getNewBillNo()));
        if(!billNoCheckFlag){
            //单号做唯一校验
            boolean billNoFlag = checkRepeatBillNo(req.getBillNo());
            if(!billNoFlag){
                return R.buildError(ResultStatusEnum.BILL_NO_REPEAT);
            }
        }
        //数量校验
        if(!CollectionUtils.isEmpty(req.getDetails())){
            if(req.getType().equals(1)){
                //登记
                boolean flag = checkProductAmount(req.getDetails(), req.getId());
                if(!flag){
                    return R.buildError(ResultStatusEnum.RESOURCE_SAMPLE_REGISTRATION_AMOUNT_ERROR);
                }
            }else if(req.getType().equals(2)){
                //领出
                boolean flag = checkProductTackAmount(req.getDetails(), req.getId());
                if(!flag){
                    return R.buildError(ResultStatusEnum.TACK_SAMPLE_REGISTRATION_AMOUNT_ERROR);
                }
            }

        }
        //第一步：主表新增、修改
        Integer id = addOrUpdate(req, creator, createNo);
        if(null == id){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

        //第二步：资源样品明细新增以及更新资源样品明细数量
        insertDetail(req, id);

        return R.build(ResultStatusEnum.SUCCESS);
    }

    /**
     * 校验登记数量是否大于剩余数量 true:否  false:是
     * @param details 明细数据
     * @param id 单据主id
     * @return 登记数量是否大于剩余数量 true:否  false:是
     */
    private boolean checkProductAmount(List<AddResourceSamplesDetailReq> details, Integer id){
        boolean flag = true;
        for(AddResourceSamplesDetailReq detailReq : details){
            PurchaseSampleUsedReq req = new PurchaseSampleUsedReq();
            req.setProductCode(detailReq.getProductCode());
            req.setLotNo(detailReq.getLotNo());
            req.setSpecificationCode(detailReq.getSpecificationCode());
            req.setSupplierCode(detailReq.getSupplierCode());
            //采购样品总量
            BigDecimal purchaseSampleAmount = new BigDecimal("0");
            BigDecimal purchaseSampleAmountTemp = resourceSamplesDetailService.getPurchaseSampleAmount(req);
            if(StringUtil.isNotEmpty(purchaseSampleAmountTemp)){
                purchaseSampleAmount = purchaseSampleAmountTemp;
            }else {
                //表明不是通过导入采购样品的数据 直接跳过校验
                continue;
            }

            //已登记数量
            BigDecimal purchaseSampleUsedAmount = new BigDecimal("0");
            BigDecimal purchaseSampleUsedAmountTemp = resourceSamplesDetailService.getPurchaseSampleUsedAmount(req);
            if(StringUtil.isNotEmpty(purchaseSampleUsedAmountTemp)){
                purchaseSampleUsedAmount = purchaseSampleUsedAmountTemp;
            }
            if(null != id && null != detailReq.getId()){
                ResourceSamplesDetailEntity product = resourceSamplesDetailService.queryById(detailReq.getId());
                BigDecimal oldNum = new BigDecimal("0");
                if(null != product && StringUtil.isNotEmpty(product.getProductNum())){
                    oldNum = product.getProductNum();
                }
                //修改:已登记数量-修改前登记数量
                purchaseSampleUsedAmount = purchaseSampleUsedAmount.subtract(oldNum);
            }

            //剩余数量
            BigDecimal lastAmount = purchaseSampleAmount.subtract(purchaseSampleUsedAmount);

            //本次登记数量
            BigDecimal productNum = new BigDecimal("0");
            if(StringUtil.isNotEmpty(detailReq.getProductNum())){
                productNum = detailReq.getProductNum();
            }

            if(productNum.compareTo(lastAmount) == 1){
                flag = false;
                break;
            }

        }
        return flag;
    }

    /**
     * 校验登出数量是否大于剩余数量 true:否  false:是
     * @param details 明细数据
     * @param id 单据主id
     * @return 登出数量是否大于剩余数量 true:否  false:是
     */
    private boolean checkProductTackAmount(List<AddResourceSamplesDetailReq> details, Integer id){
        boolean flag = true;
        for(AddResourceSamplesDetailReq detailReq : details){
            TheSameResourceSamplesInfoReq req = new TheSameResourceSamplesInfoReq();
            //赋值
            BeanUtils.copyProperties(detailReq, req);
            req.setType(1);
            List<Integer> statusRegistration = new ArrayList<>();
            statusRegistration.add(3);
            statusRegistration.add(4);
            req.setStatus(statusRegistration);
            //登记数量
            BigDecimal registrationSum = new BigDecimal("0");
            BigDecimal registrationSumTemp = resourceSamplesDetailService.getTheSameResourceSamplesInfo(req);
            if(StringUtil.isNotEmpty(registrationSumTemp)){
                registrationSum = registrationSumTemp;
            }

            req.setType(2);
            List<Integer> statusTack = new ArrayList<>();
            statusTack.add(1);
            statusTack.add(2);
            statusTack.add(3);
            statusTack.add(4);
            statusTack.add(5);
            req.setStatus(statusTack);

            //已领出数量
            BigDecimal tackSum = new BigDecimal("0");
            BigDecimal tackSumTemp = resourceSamplesDetailService.getTheSameResourceSamplesInfo(req);
            if(StringUtil.isNotEmpty(tackSumTemp)){
                tackSum = tackSumTemp;
            }

            if(null != id && null != detailReq.getId()){
                ResourceSamplesDetailEntity product = resourceSamplesDetailService.queryById(detailReq.getId());
                BigDecimal oldNum = new BigDecimal("0");
                if(null != product && StringUtil.isNotEmpty(product.getProductNum())){
                    oldNum = product.getProductNum();
                }
                //修改:已领出数量-修改前领出数量
                tackSum = tackSum.subtract(oldNum);
            }

            //剩余数量
            BigDecimal lastSum = registrationSum.subtract(tackSum);

            //当前需要领出数量
            BigDecimal needTackSum = new BigDecimal("0");
            if(StringUtil.isNotEmpty(detailReq.getProductNum())){
                needTackSum = detailReq.getProductNum();
            }

            if(needTackSum.compareTo(lastSum) == 1){
                flag = false;
                break;
            }

        }
        return flag;
    }

    /**
     * 明细新增
     * @param req 入参
     * @param id 出库id
     */
    public void insertDetail(AddResourceSamplesReq req, Integer id){
        if(!CollectionUtils.isEmpty(req.getDetails())){
            //获取修改明细id集合
            List<Integer> newIds = new ArrayList<>();
            //新增明细集合
            List<ResourceSamplesDetailEntity> addDetails = new ArrayList<>();
            for(AddResourceSamplesDetailReq detailReq : req.getDetails()){
                //资源样品明细对象
                ResourceSamplesDetailEntity detail = new ResourceSamplesDetailEntity();
                //赋值
                BeanUtils.copyProperties(detailReq, detail);
                //设置id
                detail.setParentId(id);
                //设置数据有效性(0:无效 1:有效)
                detail.setValid(DataIsValidEnum.VALID.getId());
                if(null == detailReq.getId()){
                    //新增
                    //创建时间
                    detail.setCreateDate(new Date());
                    addDetails.add(detail);
                }else {
                    //修改
                    //获取明细id
                    newIds.add(detailReq.getId());
                    detail.setModifyTime(new Date());
                    resourceSamplesDetailService.update(detail);
                }

            }

            //处理被删除的资源样品明细
            handleBeenDeletedTransferDetail(req, id, newIds);

            if(!CollectionUtils.isEmpty(addDetails)){
                //调用接口保存资源样品明细
                resourceSamplesDetailService.addList(addDetails);
            }
        }
    }

    /**
     * 处理被删除的明细
     * @param req 明细
     * @param id id
     * @param newIds 修改后未被删除的入库明细id集合
     */
    private void handleBeenDeletedTransferDetail(AddResourceSamplesReq req, int id, List<Integer> newIds){
        if(null != req.getId()){
            //修改-找出被删除的入库明细

            ResourceSamplesDetailEntity resourceSamplesDetail = new ResourceSamplesDetailEntity();
            //设置入库id
            resourceSamplesDetail.setParentId(id);
            //查询有效数据
            resourceSamplesDetail.setValid(DataIsValidEnum.VALID.getId());
            //调用接口查询结果
            List<ResourceSamplesDetailEntity> details = resourceSamplesDetailService.queryAll(resourceSamplesDetail);
            if(!CollectionUtils.isEmpty(details)){
                //获取id集合
                List<Integer> oldIds = details.stream().map(p -> p.getId()).collect(Collectors.toList());
                //找出被删除的id
                Collection collection = new ArrayList(oldIds);
                collection.removeAll(newIds);
                if(collection.size() > 0){
                    //遍历删除被删除的明细
                    Iterator<Integer> ids = collection.iterator();
                    while (ids.hasNext()){
                        int deletedId = ids.next();
                        //初始化参数
                        ResourceSamplesDetailEntity updateReq = new ResourceSamplesDetailEntity();
                        //删除的是待批和草稿箱数据，直接将数据设为无效
                        updateReq.setId(deletedId);
                        //将数据设为无效
                        updateReq.setValid(DataIsValidEnum.INVALID.getId());
                        //调用接口修改
                        resourceSamplesDetailService.update(updateReq);
                    }
                }
            }
        }
    }

    /**
     * 获取详情、修改
     * @param id 登记id
     * @return
     */
    public ResourceSamplesDetailVo getDetailInfo(Integer id){
        //初始化回参实体
        ResourceSamplesDetailVo vo = new ResourceSamplesDetailVo();
        if(null == id){
            return vo;
        }

        //第一步：获取主表信息
        ResourceSamplesEntity resourceSamples = resourceSamplesService.queryById(id);
        if(null == resourceSamples || null == resourceSamples.getId()){
            return vo;
        }
        //赋值
        BeanUtils.copyProperties(resourceSamples, vo);
        //设置创建时间
        vo.setCreateDate(DateUtils.format(resourceSamples.getCreateDate(), DateUtils.DATE_PATTERN));
        //设置业务类型
        vo.setTypeStr(ResourceSamplesTypeEnum.getDescById(vo.getType()));

        //第二步：获取对应产品信息
        ResourceSamplesDetailEntity detailReq = new ResourceSamplesDetailEntity();
        //设置入库id
        detailReq.setParentId(id);
        //设置数据为有效
        detailReq.setValid(DataIsValidEnum.VALID.getId());
        List<ResourceSamplesDetailEntity> details = resourceSamplesDetailService.queryAll(detailReq);

        if(!CollectionUtils.isEmpty(details)){
            List<ResourceSamplesProductDetailVo> productVos = details.stream().map(p -> {
                ResourceSamplesProductDetailVo productVo = new ResourceSamplesProductDetailVo();
                //赋值
                BeanUtils.copyProperties(p, productVo);

                return productVo;
            }).collect(Collectors.toList());

            vo.setDetailList(productVos);
        }
        return vo;
    }

    /**
     * 仓库管理-资源样品-批量领出
     * @param id 登记id
     * @return
     */
    public List<ImportResourceSamplesVo> getBatchRegisterDetail(String id){
        //初始化回参实体
        List<ImportResourceSamplesVo> voList = new ArrayList<>();
        if(StringUtils.isBlank(id)){
            return voList;
        }
        //存在多个id
        List<String> ids = Arrays.asList(id.split(","));
        //查询结果
        List<ResourceSamplesDetailEntity> resourceSamplesDetailList = resourceSamplesDetailService.getResourceSamplesDetailByIds(ids);
        if(CollectionUtils.isEmpty(resourceSamplesDetailList)){
            return voList;
        }
        for(ResourceSamplesDetailEntity detail : resourceSamplesDetailList){
            ImportResourceSamplesVo vo = new ImportResourceSamplesVo();
            //对象赋值
            BeanUtils.copyProperties(detail, vo);
            //领出id为登记时的主键id
            vo.setTakeOutId(detail.getId());
            //产品数量默认为空
            vo.setProductNum(new BigDecimal("0"));
            //参考数量
            vo.setNum(detail.getProductNum());

            voList.add(vo);
        }
        return voList;
    }

    /**
     * 获取资源信息
     * @param resourceSamplesDetailEntities 资源样品明细对象
     * @return key为调拨明细id value为调拨数量
     */
    private Map<Integer, Map<String, String>> getResourceSamplesMap(List<ResourceSamplesDetailEntity> resourceSamplesDetailEntities){
        //资源信息
        Map<Integer, Map<String, String>> resourceSamplesMap = new HashMap<>(resourceSamplesDetailEntities.size());
        for(ResourceSamplesDetailEntity detailEntity : resourceSamplesDetailEntities){
            Map<String, String> info = new HashMap<>(8);
            //产品编码
            info.put("productCode", detailEntity.getProductCode());
            //规格编码
            info.put("specificationCode", detailEntity.getSpecificationCode());
            //货号
            info.put("articleNo", detailEntity.getArticleNo());
            //批次
            info.put("lotNo", detailEntity.getLotNo());
            //仓库
            info.put("warehouseId", detailEntity.getWarehouseId());
            //供应商
            info.put("supplierCode", detailEntity.getSupplierCode());

            resourceSamplesMap.put(detailEntity.getId(), info);
        }
        return resourceSamplesMap;
    }

    /**
     * 获取资源信息
     * @param resourceSamplesDetailEntities 资源样品明细对象
     * @return key为调拨明细id value为调拨数量
     */
    private Map<Integer, Map<String, BigDecimal>> getQuantityMap(List<ResourceSamplesDetailEntity> resourceSamplesDetailEntities){
        //数量
        Map<Integer, Map<String, BigDecimal>> productNumMap = new HashMap<>(resourceSamplesDetailEntities.size());
        for(ResourceSamplesDetailEntity detailEntity : resourceSamplesDetailEntities){
            Map<String, BigDecimal> info = new HashMap<>(8);
            //数量
            info.put("productNum", detailEntity.getProductNum());
            //单价
            info.put("unitPrice", detailEntity.getUnitPrice());

            productNumMap.put(detailEntity.getId(), info);
        }
        return productNumMap;
    }

    /**
     * 新增、修改
     * @param req 参数实体
     * @param creator 创建人
     * @param createNo 创建人编码
     * @return 新增、修改结果
     */
    private Integer addOrUpdate(AddResourceSamplesReq req, String creator, String createNo){
        //初始化对象
        ResourceSamplesEntity data = new ResourceSamplesEntity();
        //赋值
        BeanUtils.copyProperties(req, data);
        //设置创建人
        data.setOperator(creator);
        //设置创建人编码
        data.setOperationNo(createNo);
        //修改时间
        data.setModifyTime(new Date());
        //设置状态,默认为草稿箱
        data.setStatus(OperationStatusEnum.DRAFT_BOX.getId());

        if(null == req.getId()){
            //新增
            //创建日期
            data.setCreateDate(new Date());
            //设置有效性
            data.setValid(DataIsValidEnum.VALID.getId());
            //调用接口新增
            resourceSamplesService.insert(data);
        }else {
            //修改
            resourceSamplesService.update(data);
        }
        return data.getId();
    }

    /**
     * 校验单号是否存在
     * @param billNo 单号
     * @return true:不重复 false:重复
     */
    private boolean checkRepeatBillNo(String billNo){
        ResourceSamplesEntity req = new ResourceSamplesEntity();
        req.setBillNo(billNo);
        List<ResourceSamplesEntity> list = resourceSamplesService.queryAll(req);
        if(CollectionUtils.isEmpty(list)){
            return true;
        }
        return false;
    }

    /**
     * 获取所有资源仓库字典信息
     * @return 仓库字典信息
     */
    public List<DictionaryInfoVo> getDictionaryInfo(DictionaryInfoReq dictionaryInfosReq){
        //初始化回参
        List<DictionaryInfoVo> dictionaryVos = new ArrayList<>();
        List<DictionaryInfoRsp> dictionaryInfos = stockService.getDictionaryInfo(dictionaryInfosReq);
        if(CollectionUtils.isEmpty(dictionaryInfos)){
            return dictionaryVos;
        }
        for(DictionaryInfoRsp infoRsp : dictionaryInfos){
            DictionaryInfoVo vo = new DictionaryInfoVo();
            BeanUtils.copyProperties(infoRsp, vo);

            dictionaryVos.add(vo);
        }

        return dictionaryVos;
    }

    /**
     * 仓库管理-资源样品-领出-导入资源仓库信息
     * @param req 查询条件
     * @return 产品集合
     */
    public PageInfo<ImportResourceSamplesVo> getTakeOutProductInfoByPage(ImportResourceSamplesReq req){
        //初始化查询参数实体
        ImportResourceSamplesProductReq productInfoReq = new ImportResourceSamplesProductReq();
        //字段赋值
        BeanUtils.copyProperties(req, productInfoReq);
        //调用接口查询结果
        List<ResourceSamplesDetailEntity> productInfoList = resourceSamplesDetailService.getResourceSamplesDetailInfo(productInfoReq);
        //初始化回参对象集合
        List<ImportResourceSamplesVo> infoVos = new ArrayList<>();
        //获取分页信息
        PageInfo pageInfo = new PageInfo(productInfoList);
        if(CollectionUtils.isEmpty(productInfoList)){
            pageInfo.setList(infoVos);
            return pageInfo;
        }
        for(ResourceSamplesDetailEntity infoRsp : productInfoList){
            //初始化回参对象
            ImportResourceSamplesVo vo = new ImportResourceSamplesVo();
            //赋值
            BeanUtils.copyProperties(infoRsp, vo);
            //参考数量
            vo.setNum(infoRsp.getProductNum());

            infoVos.add(vo);
        }
        pageInfo.setList(infoVos);
        return pageInfo;
    }

    /**
     * 删除(修改数据有效性)
     * @param id id
     * @param status 状态(1.草稿箱 2.待批箱 3.已批箱 4.完成箱 5.垃圾箱)
     */
    @Transactional(rollbackFor = Exception.class)
    public R delete(Integer id, Integer status){
        if(null == id){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        ResourceSamplesEntity resourceSamples = new ResourceSamplesEntity();
        //修改主键
        resourceSamples.setId(id);
        //设置修改时间
        resourceSamples.setModifyTime(new Date());
        if(OperationStatusEnum.DRAFT_BOX.getId() == status){
            //草稿箱删除：数据设为垃圾箱
            resourceSamples.setStatus(OperationStatusEnum.TRASH_CAN.getId());
            resourceSamplesService.update(resourceSamples);
            return R.build(ResultStatusEnum.SUCCESS);
        }else if(OperationStatusEnum.TRASH_CAN.getId() == status){
            //垃圾箱删除：数据设为无效
            resourceSamples.setValid(DataIsValidEnum.INVALID.getId());
            resourceSamplesService.update(resourceSamples);
        }

        //获取明细数据
        ResourceSamplesDetailEntity detailReq = new ResourceSamplesDetailEntity();
        detailReq.setParentId(id);
        detailReq.setValid(DataIsValidEnum.VALID.getId());
        //获取明细
        List<ResourceSamplesDetailEntity> details = resourceSamplesDetailService.queryAll(detailReq);
        if(CollectionUtils.isEmpty(details)){
            //没有明细,只删除主表数据
            return R.build("");
        }
        for(ResourceSamplesDetailEntity detail : details){
            //明细数据全部设为无效
            ResourceSamplesDetailEntity detailEntity = new ResourceSamplesDetailEntity();
            //设置修改id
            detailEntity.setId(detail.getId());
            //设置修改时间
            detailEntity.setModifyTime(new Date());
            //数据设为无效
            detailEntity.setValid(DataIsValidEnum.INVALID.getId());
            //更新数据
            resourceSamplesDetailService.update(detailEntity);
        }
        return R.build("");
    }

    /**
     * 数据操作接口
     * @param id id
     * @param type 1:登记 2:领出
     * @param operation 操作类型
     * 1.提交审批 2.审批通过 3.审批退回 4.完成 5.还原
     * 箱体：1.草稿箱 2.待批箱 3.已批箱 4.完成箱 5.垃圾箱
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public R operation(Integer id, Integer type, Integer operation){
        if(null == id || null == type || null == operation){
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
        ResourceSamplesEntity resourceSamples = new ResourceSamplesEntity();
        //设置id
        resourceSamples.setId(id);
        if(operation == SubmitStatusEnum.SUBMIT_APPROVE.getId()){
            //提交审批后,状态为待批箱
            //状态设为待批箱
            resourceSamples.setStatus(OperationStatusEnum.PENDING_BOX.getId());
        }else if(operation == SubmitStatusEnum.APPROVE_SUCCESS.getId()){
            //审批通过
            resourceSamples.setStatus(OperationStatusEnum.APPROVED_BOX.getId());
        }else if(operation == SubmitStatusEnum.APPROVE_RETURN.getId()){
            //审批退回后只修改调拨状态
            //状态设为草稿箱
            resourceSamples.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        }else if(operation == SubmitStatusEnum.SUCCESS.getId()){
            //将状态设为完成
            resourceSamples.setStatus(OperationStatusEnum.COMPLETION_BOX.getId());
        }else if(operation == SubmitStatusEnum.REDUCTION.getId()){
            //将状态改为草稿箱
            resourceSamples.setStatus(OperationStatusEnum.DRAFT_BOX.getId());
        }
        //修改数据
        resourceSamplesService.update(resourceSamples);
        return R.build("");
    }

    /**
     * 获取采购样品主信息
     *
     * @param req 查询参数
     * @return 采购样品主信息
     */
    public PageInfo<ImportPurchaseSampleRsp> getPurchaseSampleInfoByPage(ImportPurchaseSampleReq req) {
        //去除前后空格
        if (StringUtils.isNotEmpty(req.getPurchaseNo())) {
            req.setPurchaseNo(req.getPurchaseNo().trim());
        }
        if (StringUtils.isNotEmpty(req.getSupplierName())) {
            req.setSupplierName(req.getSupplierName().trim());
        }
        List<ImportPurchaseSampleRsp> purchaseSampleRspList = resourceSamplesDetailService.getImportPurchaseSampleInfo(req);
        //获取分页信息
        PageInfo pageInfo = new PageInfo(purchaseSampleRspList);
        pageInfo.setList(purchaseSampleRspList);

        return pageInfo;
    }

    /**
     * 通过采购样品主ID获取对应产品信息
     *
     * @param id 采购样品主ID
     * @return 采购样品产品信息
     */
    public List<ImportPurchaseSampleProductRsp> getPurchaseSampleProductById(Integer id) {
        List<ImportPurchaseSampleProductRsp> productList = new ArrayList<>();
        if(null == id){
            return productList;
        }
        productList = resourceSamplesDetailService.getPurchaseSampleProductById(id);

        return productList;
    }

    /**
     * 通过采购单号获取已做样品登记数量
     *
     * @param purchaseNo 采购单号
     * @return 已做样品登记数量
     */
    public int getResourceSampleCountByPurchaseNo(String purchaseNo) {
        if (StringUtils.isEmpty(purchaseNo)) {
            return 0;
        }
        ResourceSamplesDetailEntity req = new ResourceSamplesDetailEntity();
        req.setLotNo(purchaseNo);
        req.setValid(DataIsValidEnum.VALID.getId());
        List<ResourceSamplesDetailEntity> list = resourceSamplesDetailService.queryAll(req);
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }
        return list.size();
    }

    /**
     * 通过id获取已做样品领出数量
     * @param id 单据主id
     * @return 已做样品领出数量
     */
    public int getSampleTakeCountById(Integer id) {
        if (null == id) {
            return 0;
        }
        ResourceSamplesDetailEntity req = new ResourceSamplesDetailEntity();
        req.setParentId(id);
        req.setValid(DataIsValidEnum.VALID.getId());
        List<ResourceSamplesDetailEntity> list = resourceSamplesDetailService.queryAll(req);
        if(CollectionUtils.isEmpty(list)){
            return 0;
        }
        //已领出数量
        BigDecimal tackSum = new BigDecimal("0");
        for(ResourceSamplesDetailEntity detail : list){
            TheSameResourceSamplesInfoReq queryReq = new TheSameResourceSamplesInfoReq();
            //赋值
            BeanUtils.copyProperties(detail, queryReq);

            queryReq.setType(2);
            List<Integer> statusTack = new ArrayList<>();
            statusTack.add(1);
            statusTack.add(2);
            statusTack.add(3);
            statusTack.add(4);
            statusTack.add(5);
            queryReq.setStatus(statusTack);

            BigDecimal tackSumTemp = resourceSamplesDetailService.getTheSameResourceSamplesInfo(queryReq);
            if(StringUtil.isNotEmpty(tackSumTemp)){
                tackSum = tackSumTemp.add(tackSum);
            }

        }
        return tackSum.intValue();
    }
}
